package cn.demo.mq.rpc;

import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @author Mr.Still
 * @version 1.0.0
 * @date 2021-10-18 22:16
 **/
public class RPCServer {

    private static final String RPC_QUEUE_NAME = "rpc_queue";


    /**
     * 计算斐波那契数列
     */
    private static int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("8.129.129.84");
        factory.setPort(5672);
        factory.setVirtualHost("/demo");
        factory.setUsername("user");
        factory.setPassword("password");

        try {
            //2.创建连接对象
            final Connection connection = factory.newConnection();

            //3.创建通道
            final Channel channel = connection.createChannel();

            channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
            //限制消息条数
            int prefetchCount = 1;
            channel.basicQos(prefetchCount);

            System.out.println("RPC requests");

            //获取消息
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                AMQP.BasicProperties relyProps = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(delivery.getProperties().getCorrelationId())
                        .build();

                String response = "";

                try {
                    //接受客户端消息

                    String message = new String(delivery.getBody(), StandardCharsets.UTF_8);

                    int n = Integer.parseInt(message);
                    System.out.println("[.] fib(" + message + ")");
                    response += fib(n);
                } catch (Exception e) {
                    System.out.println("[.]"+e.toString());
                } finally {
                    channel.basicPublish("",delivery.getProperties().getReplyTo(),relyProps,response.getBytes(StandardCharsets.UTF_8));
                    //手动回执
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                }
            };

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
